package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.BannedUserCache;
import com.conversationboard.model.User;

@WebServlet(name = "AdminBanRangeControllerServlet", urlPatterns = "/Admin/AdminBanRangeControllerServlet")
public class AdminBanRangeControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 1009676145464301958L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String adminId = request.getUserPrincipal().getName();
		String pattern = request.getParameter("pattern").trim();
		int boardId = Integer.parseInt(request.getParameter("board"));

		try {

			/* Check if you're authorised */
			User user = User.get(adminId);

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (!user.isSiteAdmin()) {
				return;
			}

			/* User is authorised. Ban the range permanently */

			if (pattern.length() > 0) {
				BannedUserCache.ban(user, pattern, pattern, true, true, boardId, 0, null, true);
			}

			request.setAttribute("message", "Pattern successfully banned.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
